package com.example.musicdemo.ui.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.app.DownloadManager
import android.app.DownloadManager.Request
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.widget.Toast
import androidx.appcompat.view.menu.MenuPopupHelper
import androidx.appcompat.widget.PopupMenu
import androidx.core.app.ActivityCompat
import com.example.musicdemo.R
import com.example.musicdemo.adapter.SearchAdapter
import com.example.musicdemo.base.BaseListFragment
import com.example.musicdemo.model.Music
import com.example.musicdemo.presenter.impl.SearchPresenterImp
import com.example.musicdemo.presenter.interf.SearchPresenter
import com.example.musicdemo.service.AudioService.Companion.FROM_FRAGMENT
import com.example.musicdemo.ui.activity.AudioPlayActivity
import com.example.musicdemo.util.HttpUtil
import com.example.musicdemo.widget.SearchItemView
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.jetbrains.anko.noButton
import org.jetbrains.anko.support.v4.alert
import org.jetbrains.anko.yesButton
import java.io.IOException
import java.lang.Exception
import java.lang.reflect.Field


class SearchFragment : BaseListFragment<List<Music>, Music, SearchItemView>() {
    init {
        println("打印东西吗")
        SearchAdapter().also { mAdapter = it }
    }

    private var mAdapter: SearchAdapter? = null


    override fun getSpecialPresenter(): SearchPresenter {
        return SearchPresenterImp(this)
    }

    override fun getList(response: List<Music>?): List<Music>? {
        return response
    }

    override fun getSpecialAdapter(): SearchAdapter {
        return mAdapter!!
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mAdapter?.setMyListener { list, position ->
            val intent = Intent(this.activity, AudioPlayActivity::class.java)
            handlePermission()
            intent.putExtra("position", position)
            intent.putExtra("list", list)
            intent.putExtra("from", FROM_FRAGMENT)
            startActivity(intent)
        }
        val downManager = context?.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

        mAdapter?.setLongListener { list, position, itemView ->
            val popupMenu = context?.let { view?.let { it1 -> PopupMenu(it, it1) } }
            popupMenu?.menuInflater?.inflate(R.menu.menu_list_item, popupMenu.menu)

            popupMenu?.setOnMenuItemClickListener {
                when (it.itemId) {
                    R.id.item_download -> {
                        Thread {
                            try {


                                val url =
                                    "http://gochiusa.top:3000/song/download/url?id=${list[position].id}"

                                HttpUtil.sClient.newCall(HttpUtil.getRequest(url)).enqueue(object :
                                    Callback {
                                    override fun onFailure(call: Call, e: IOException) {

                                        "这失败了"
                                    }

                                    override fun onResponse(call: Call, response: Response) {
                                        myToast("这是啥")
                                    }
                                })
                                val request =
                                    Request(Uri.parse("http://gochiusa.top:3000/song/download/url?id=${list[position].id}"))
                                println("我看看${list.get(position).id}")
                                //设置在什么网络情况下进行下载
                                //设置通知栏标题
                                request.addRequestHeader(
                                    "cookie",
                                    "MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/eapi/clientlog;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/api/clientlog;;__csrf=f6732d042976e554b22d2de140c8e53d; Max-Age=1296010; Expires=Sat, 4 Dec 2021 10:43:24 GMT; Path=/;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/weapi/clientlog;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/neapi/feedback;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/weapi/feedback;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/neapi/feedback;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/weapi/feedback;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/weapi/clientlog;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/eapi/feedback;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/neapi/clientlog;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/openapi/clientlog;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/wapi/clientlog;;MUSIC_U=cce3d9f132f1da1cd5c335ed98d3e93a192b548c2aee713328935511c9229eab519e07624a9f0053d78b6050a17a35e705925a4e6992f61d07c385928f88e8de; Max-Age=1296000; Expires=Sat, 4 Dec 2021 10:43:14 GMT; Path=/;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/wapi/feedback;;__remember_me=true; Max-Age=1296000; Expires=Sat, 4 Dec 2021 10:43:14 GMT; Path=/;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/eapi/clientlog;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/api/feedback;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/api/feedback;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/wapi/clientlog;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/openapi/clientlog;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/wapi/feedback;;MUSIC_R_T=1634384564644; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/eapi/feedback;;MUSIC_A_T=1634384564287; Max-Age=2147483647; Expires=Wed, 7 Dec 2089 13:57:21 GMT; Path=/api/clientlog;"
                                )
                                request.addRequestHeader(
                                    "token",
                                    "cce3d9f132f1da1cd5c335ed98d3e93a192b548c2aee713328935511c9229eab519e07624a9f0053d78b6050a17a35e705925a4e6992f61d07c385928f88e8de"
                                )
                                request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                                request.setTitle("下载")
                                request.setDescription("${list[position].name}正在下载")


                                request.setAllowedOverRoaming(false)
                                //设置文件存放目录
                                //设置文件存放目录
                                request.setDestinationInExternalFilesDir(
                                    context,
                                    Environment.DIRECTORY_DOWNLOADS,
                                    "myDown"
                                )
                                val id = downManager.enqueue(request)
                                myToast("开始下载了吗 $id")

                            } catch (e: Exception) {

                            }

                        }.start()


                    }
                }

                true
            }

            itemView.apply {
                popupMenu?.let { showPopupMenu(itemView.x, itemView.y, it) }
            }
        }
    }


    @SuppressLint("RestrictedApi")
    private fun showPopupMenu(x: Float, y: Float, popupMenu: PopupMenu) {

        //创建弹出式菜单对象（最低版本11）
        //绑定菜单项的点击事件


        try {
            val field: Field? = popupMenu.javaClass.getDeclaredField("mPopup")
            field?.isAccessible = true
            val helper: MenuPopupHelper = field?.get(popupMenu) as MenuPopupHelper
            val y1 = y - view?.height!!//如果y取的是触摸点的位置，可能需要作此处理，经测试android5.1的设备会弹窗在屏幕之外

            helper.show(x.toInt(), y1.toInt())
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    }


    companion object
    class DownLoadCompleteReceiver : BroadcastReceiver() {


        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
                Toast.makeText(context, "$id 下载好了", Toast.LENGTH_SHORT).show()
            } else if (intent?.action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
                Toast.makeText(context, "别瞎搞", Toast.LENGTH_LONG).show()
            }
        }
    }


    /**
     *
     */
    private fun handlePermission() {
        val permission = Manifest.permission.WRITE_EXTERNAL_STORAGE
        //查看是否有权限
        val checkSelfPermission =
            context?.let { ActivityCompat.checkSelfPermission(it, permission) }
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) {
            download()
        } else {
            if (activity?.let {
                    ActivityCompat.shouldShowRequestPermissionRationale(
                        it,
                        permission
                    )
                } == true) {
                alert("我们只会访问音乐文件", "温馨提醒") {
                    yesButton { myRequestPermission() }
                    noButton { }
                }.show()

            } else {
                myRequestPermission()
            }
        }
    }

    /**
     * 加载音乐
     */
    private fun download() {

    }


    /**
     * 接受权限授权结果
     * requestCode 请求码
     * permissions 权限申请数组
     * grantResults 申请之后结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            download()
        }
    }


    /**
     * 真正申请权限
     */
    private fun myRequestPermission() {
        val permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        requestPermissions(permissions, 1)
    }
}
